﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BDGetQuote.Web.Models;
using BDGetQuote.Utilities;
using BDGetQuote.Web.App_Start;
using System.IO;
using System.Text;

namespace BDGetQuote.Web.Controllers
{
    public class ManufacturerController : BaseController
    {
        private IManufacturerRepository _manufacturerRepository;
        private IDeletedManufacturerByCustomerRepository _deletedManufacturerByCustomerRepository;
        public ManufacturerController()
        {
            _manufacturerRepository = new ManufacturerRepository();
            _deletedManufacturerByCustomerRepository = new DeletedManufacturerByCustomerRepository();
        }
        // GET: /Manufacturer/
        public ActionResult Index()
        {
            var _user = (UserInfo)Session[Constants.SessionUser];
            var listManufacturers = _manufacturerRepository.GetAll(_user.UserId);
            return View(listManufacturers);
        }
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            var _user = (UserInfo)Session[Constants.SessionUser];
            ViewBag.Keyword = form["txtKeyword"] + "";
            var listManufacturers = _manufacturerRepository.GetAll(_user.UserId, ViewBag.Keyword);
            
            return View(listManufacturers);
        }
        public ActionResult Edit(int? id)
        {
            ViewBag.DomainUrl = Helper.GetDomainUrl();
            var _user = (UserInfo)Session[Constants.SessionUser];
            Manufacturer _item = null;
            if (id.HasValue)
            {
                _item = _manufacturerRepository.GetById(id.Value, _user.UserId);
            }
            if (_item !=null)
            {
                ViewBag.Title = "Edit Manufacturer";
            }
            else
            {
                ViewBag.Title = "Add Manufacturer";
                _item = new Manufacturer();
                if (_user.IsAdmin)
                {
                    _item.IsSystem = true;
                }
            }
            
            return View("Edit",_item);
        }
        [HttpPost]
        public ActionResult Edit(Manufacturer model)
        {
            if (!ModelState.IsValid)
                return View(model);
            var _user = (UserInfo)Session[Constants.SessionUser];
            if (Request.Files["uplLogo"].ContentLength > 0)
            {
                if (Request.Files["uplLogo"].ContentLength <= Constants.MaxImageUploadFile)
                {
                    string _extension = System.IO.Path.GetExtension(Request.Files["uplLogo"].FileName);
                    switch (_extension.ToLower())
                    {
                        case ".jpg":
                        case ".jpeg":
                        case ".png":
                        case ".gif":
                        case ".tiff":
                        case ".ico":
                            string _imageName = model.Name.Replace(" ", "-") + "_" + Guid.NewGuid().ToString();
                            string _phisicalPath = string.Format("{0}\\{1}{2}", Server.MapPath("~/" + Constants.FolderManufacturerImage), _imageName, _extension);
                            string _imageUrl = Constants.FolderManufacturerImage + "/" + _imageName + _extension;
                            if (!String.IsNullOrEmpty(model.ImageUrl) && System.IO.File.Exists(Server.MapPath("~/" + model.ImageUrl)))
                                System.IO.File.Delete(Server.MapPath("~/" + model.ImageUrl));

                            Request.Files["uplLogo"].SaveAs(_phisicalPath);
                            model.ImageUrl = _imageUrl;
                            break;
                        default:
                            ViewBag.ErrorMessage = "Error occurs! Your upload file is not image (*.jpg,*.jpeg,*.png,*.gif,...)";
                            return View(model);
                    }
                }
                else
                {
                    ViewBag.ErrorMessage = "Error occurs! Maximum of Image size is " + (Constants.MaxImageUploadFile / (1024 * 1024)) + " MB";
                    return View(model);
                }
            }
            // Hack date to serialize
            model.CreatedDate = DateTime.Now;
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(model.GetType());
            MemoryStream ms = new MemoryStream();
            
            if (model.ManufacturerId > 0)
            {
                _manufacturerRepository.Edit(model);
                serializer.WriteObject(ms, model);
                string jsonModel = Encoding.Default.GetString(ms.ToArray());
                ViewBag.InitialScript = String.Format("<script type='text/javascript'>window.parent.EditManufacturer({0});</script>", jsonModel);
            }
            else
            {
                model.CreatedBy = _user.UserId;
                if (_user.IsAdmin)
                {
                    model.IsSystem = true;
                }
                model.ManufacturerId = _manufacturerRepository.Add(model);
                serializer.WriteObject(ms, model);
                string jsonModel = Encoding.Default.GetString(ms.ToArray());
                ViewBag.InitialScript = String.Format("<script type='text/javascript'>window.parent.AddManufacturer({0});</script>", jsonModel);
            }
            return View(model);
        }
        public JsonResult Delete(int id)
        {
            var _user = (UserInfo)Session[Constants.SessionUser];
            var _manufacturer = _manufacturerRepository.GetById(id, _user.UserId);
            if (_manufacturer != null)
            {
                if (_manufacturer.IsSystem)
                {
                    if (_user.IsAdmin)
                    {
                        _manufacturerRepository.Delete(id);
                    }
                    else 
                    {
                        _deletedManufacturerByCustomerRepository.Add(_user.UserId, id);
                    }
                }
                else
                {
                    _manufacturerRepository.Delete(id);
                }
            }
            return Json(id, JsonRequestBehavior.AllowGet);
        }
    }
}
